"""
配置管理模块
负责保存和读取同步任务配置
"""
import json
import os
from typing import List, Dict, Any


class ConfigManager:
    """配置管理器"""
    
    def __init__(self, config_file: str = "sync_config.json"):
        self.config_file = config_file
        self.config = self._load_config()
    
    def _load_config(self) -> Dict[str, Any]:
        """加载配置文件"""
        if os.path.exists(self.config_file):
            try:
                with open(self.config_file, 'r', encoding='utf-8') as f:
                    return json.load(f)
            except Exception as e:
                print(f"加载配置文件失败: {e}")
                return {"tasks": [], "settings": self._get_default_settings()}
        return {"tasks": [], "settings": self._get_default_settings()}
    
    def _get_default_settings(self) -> Dict[str, Any]:
        """获取默认设置"""
        return {
            "auto_start": False,
            "check_interval": 1,  # 文件检查间隔（秒）
            "log_level": "INFO",
            "max_log_size": 10 * 1024 * 1024,  # 10MB
            "ignore_patterns": [
                "*.tmp",
                "*.temp",
                "~*",
                ".DS_Store",
                "Thumbs.db",
                "__pycache__/",
                ".git/",
                ".svn/",
                "node_modules/"
            ]
        }
    
    def save_config(self) -> bool:
        """保存配置文件"""
        try:
            with open(self.config_file, 'w', encoding='utf-8') as f:
                json.dump(self.config, f, ensure_ascii=False, indent=2)
            return True
        except Exception as e:
            print(f"保存配置文件失败: {e}")
            return False
    
    def add_task(self, task: Dict[str, Any]) -> bool:
        """添加同步任务"""
        if "tasks" not in self.config:
            self.config["tasks"] = []
        
        # 生成任务ID
        task_id = len(self.config["tasks"]) + 1
        task["id"] = task_id
        task["enabled"] = True
        
        self.config["tasks"].append(task)
        return self.save_config()
    
    def update_task(self, task_id: int, task: Dict[str, Any]) -> bool:
        """更新同步任务"""
        for i, t in enumerate(self.config["tasks"]):
            if t["id"] == task_id:
                task["id"] = task_id
                self.config["tasks"][i] = task
                return self.save_config()
        return False
    
    def delete_task(self, task_id: int) -> bool:
        """删除同步任务"""
        self.config["tasks"] = [t for t in self.config["tasks"] if t["id"] != task_id]
        return self.save_config()
    
    def get_tasks(self) -> List[Dict[str, Any]]:
        """获取所有任务"""
        return self.config.get("tasks", [])
    
    def get_task(self, task_id: int) -> Dict[str, Any]:
        """获取指定任务"""
        for task in self.config["tasks"]:
            if task["id"] == task_id:
                return task
        return None
    
    def get_settings(self) -> Dict[str, Any]:
        """获取设置"""
        return self.config.get("settings", self._get_default_settings())
    
    def update_settings(self, settings: Dict[str, Any]) -> bool:
        """更新设置"""
        self.config["settings"] = settings
        return self.save_config()


